package com.feiyue.learning.order_service.listener;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ArrayList;
import java.util.List;

public class InitListener implements ServletContextListener {
    private static Logger LOGGER = LoggerFactory.getLogger(InitListener.class);
    private static final String ZK_CONNECTION = "127.0.0.1:2181";
    private static final String BASE_SERVICE = "/service";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
       init();
    }

    public void init() {
        ZkClient zkClient = new ZkClient(ZK_CONNECTION, 5000);
        IZkChildListener listener = (a, b) -> {
            if (BASE_SERVICE.equals(a)) {
                updateServiceList(zkClient);
            }
        };

        // 监听注册中心服务的变化
        zkClient.subscribeChildChanges(BASE_SERVICE, listener);
        updateServiceList(zkClient);
    }

    public void updateServiceList(ZkClient zkClient) {
        List<String> serviceList = new ArrayList<>(8);
        List<String> children = zkClient.getChildren(BASE_SERVICE);
        for (String child : children) {
            LOGGER.info("child path: {}", child);
            String service = zkClient.readData(BASE_SERVICE.concat("/").concat(child));
            serviceList.add(service);
        }
        serviceList.forEach(r->System.out.print(r + ", "));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
